<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车牌" prop="carNumber">
        <el-input
          v-model="queryParams.carNumber"
          placeholder="请输入车牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目类型" prop="maintenanceRecordType">
        <el-select v-model="queryParams.maintenanceRecordType" placeholder="请选择项目类型" clearable>
          <el-option
            v-for="dict in dict.type.maintenance_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="维修保养消费金额" prop="maintenanceRecordPrice">
        <el-input
          v-model="queryParams.maintenanceRecordPrice"
          placeholder="请输入维修保养消费金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
                        v-model="queryParams.createTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择创建时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="maintenanceStatus">
        <el-select v-model="queryParams.maintenanceStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.maintenance_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['car:record:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['car:record:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['car:record:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['car:record:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" align="center" prop="maintenanceRecordId"/>
      <el-table-column label="车牌" align="center" prop="carNumber"/>
      <el-table-column label="项目类型" align="center" prop="maintenanceRecordType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.maintenance_type" :value="scope.row.maintenanceRecordType"/>
        </template>
      </el-table-column>
      <el-table-column label="维保金额" align="center" prop="maintenanceRecordPrice"/>
      <el-table-column label="维保时间" align="center" prop="createTime"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="状态" align="center" prop="maintenanceStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.maintenance_status" :value="scope.row.maintenanceStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['car:record:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['car:record:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维修保养记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车牌" prop="carNumber">
          <el-input v-model="form.carNumber" placeholder="请输入车牌"/>
        </el-form-item>
        <el-form-item label="项目类型" prop="maintenanceRecordType">
          <el-select v-model="form.maintenanceRecordType" placeholder="请选择项目类型">
            <el-option
              v-for="dict in dict.type.maintenance_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

          <el-table style="height: 176px; overflow-y: scroll;"
                    v-loading="loading"
                    ref="multipleTable"
                    :data="maintenanceList"
                    v-model="form.idsMaintenance"
                    :row-key="getRowKey"
                    @selection-change="handleSelectionChangeMaintenance"
          >
            <el-table-column type="selection" :reserve-selection="true" width="55" align="center"/>
            <el-table-column label="保养维修项目名称" align="center" prop="maintenanceName"/>
            <el-table-column label="维修保养价格" align="center" prop="maintenancePrice"/>
            <el-table-column label="维修/保养" align="center" prop="maintenanceType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.maintenance_type" :value="scope.row.maintenanceType"/>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            style="margin-top: 5px; margin-bottom: 30px;"
            v-show="totalMaintenance>0"
            :page-sizes="[3, 6, 9]"
            :total="totalMaintenance"
            :page.sync="queryParamsMaintenance.pageNumMaintenance"
            :limit.sync="queryParamsMaintenance.pageSizeMaintenance"
            @pagination="getListMaintenance"
          />



        <el-form-item label="维保金额" prop="maintenanceRecordPrice">
          <el-input v-model="form.maintenanceRecordPrice" placeholder="请输入维修保养消费金额"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="状态" prop="maintenanceStatus">
          <el-select v-model="form.maintenanceStatus" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.maintenance_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from '@/api/car/record'
import {
  listMaintenance,
  getMaintenance,
  delMaintenance,
  addMaintenance,
  updateMaintenance
} from '@/api/car/maintenance'

export default {
  name: 'Record',
  dicts: ['maintenance_status', 'maintenance_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的项目数组
      idsMaintenance: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalMaintenance: 0,
      // 维修保养记录表格数据
      recordList: [],
      // 维修保养表格数据
      maintenanceList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carNumber: null,
        maintenanceRecordType: null,
        maintenanceRecordPrice: null,
        createTime: null,
        maintenanceStatus: null
      },
      queryParamsMaintenance: {
        pageNumMaintenance: 1,
        pageSizeMaintenance: 3,
        maintenanceName: null,
        maintenancePrice: null,
        maintenanceType: null
      },
      // 表单参数
      form: {
        idsMaintenance: []
      },
      // 表单校验
      rules: {
        carNumber: [
          { required: true, message: '车牌不能为空', trigger: 'blur' }
        ],
        maintenanceRecordType: [
          { required: true, message: '项目类型不能为空', trigger: 'change' }
        ],
        maintenanceRecordPrice: [
          { required: true, message: '维修保养消费金额不能为空', trigger: 'blur' }
        ],
        maintenanceStatus: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getListMaintenance()
  },
  methods: {
    getListMaintenance() {
      this.loading = true
      listMaintenance(this.queryParamsMaintenance).then(response => {
        this.maintenanceList = response.rows
        this.totalMaintenance = response.total
        this.loading = false
      })
    },
    /** 查询维修保养记录列表 */
    getList() {
      this.loading = true
      listRecord(this.queryParams).then(response => {
        this.recordList = response.rows
        console.log(this.recordList)
        this.total = response.total
        this.loading = false
      })
    },
    handleSelectionChangeMaintenance(selection) {
      //console.log(selection)
      this.form.idsMaintenance = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
        this.form = {
          maintenanceRecordId: null,
          maintenanceList: [],
          carNumber: null,
          maintenanceRecordType: null,
          maintenanceRecordPrice: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          maintenanceStatus: null
        }
      this.$nextTick(function() {
        setTimeout(() => {
          this.$refs.multipleTable.clearSelection();
        }, 500)
      })
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.maintenanceRecordId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加维修保养记录'
    },
    /* toggleSelection(rows) {
      this.$nextTick(function(){
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      })
    }, */
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      //this.toggleSelection(row.maintenanceList)
      this.$nextTick(function() {
        setTimeout(() => {
          console.log(row.idsMaintenance)
          console.log(row)
          row.idsMaintenance.forEach(item => {
            this.maintenanceList.forEach(i => {
              if (item.maintenanceId === i.maintenanceId) {
                console.log('i', i)
                this.$refs.multipleTable.toggleRowSelection(i)
              }
            })
          })
        }, 1000)
      })
      const maintenanceRecordId = row.maintenanceRecordId || this.ids
      getRecord(maintenanceRecordId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改维修保养记录'
      })
    },
    getRowKey(row) {
      return row.maintenanceId
    },
    /** 提交按钮 */
    submitForm() {
      //console.log('form', this.form)
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.maintenanceRecordId != null) {
            updateRecord(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
              this.getListMaintenance()
            })
          } else {
            addRecord(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
              this.getListMaintenance()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const maintenanceRecordIds = row.maintenanceRecordId || this.ids
      this.$modal.confirm('是否确认删除维修保养记录编号为"' + maintenanceRecordIds + '"的数据项？').then(function() {
        return delRecord(maintenanceRecordIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('car/record/export', {
        ...this.queryParams
      }, `record_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
